import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Modal,
  message,
  Badge,
  Divider,
  Tag,
  Popconfirm,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './Content.less';
import { imgPrex } from '../../utils/constData';

const FormItem = Form.Item;
const { Option } = Select;
const { CheckableTag } = Tag;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['error', 'success'];
const status = ['下架', '上架'];

@connect(({ content, loading }) => ({
  content,
  contentList: content.contentList,
  pagination: content.pagination,
  loading: loading.models.content,
}))
@Form.create()
export default class Content extends PureComponent {
  state = {
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'content/fetch',
      payload: { pageNum: 1, pageSize: 10 }
    });

    this.props.dispatch({
      type: 'content/fetchAuthorList',
      payload: { pageNum: 1, pageSize: 0 },
    });
  }

  handlAdd = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push({ pathname: '/content/add/new' }));
  };

  _editContent(record) {
    this.props.dispatch(routerRedux.push({ pathname: '/content/add/' + record.goodsId }));
  }

  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;

    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.props.form.getFieldsValue(),
    };

    dispatch({
      type: 'content/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    const params = {
      pageNum: 1,
      pageSize: this.props.pagination.pageSize ? this.props.pagination.pageSize : 10,
    };
    dispatch({
      type: 'content/fetch',
      payload: params,
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch() {
    console.log('this.props.content.pagination???', this.props.content.pagination)
    const params = {
      pageNum: 1,
      pageSize: this.props.content.pagination.pageSize ? this.props.content.pagination.pageSize : 10,
      ...this.props.form.getFieldsValue(),
    };
    this.props.dispatch({
      type: 'content/fetch',
      payload: params,
      condition: this.props.form.getFieldsValue(),
    });
  }

  renderAdvancedForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form  layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="内容名称">
              {getFieldDecorator('goodsName')(<Input placeholder="请输入" maxLength={10}/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="作者">
              {getFieldDecorator('authorName')(<Input placeholder="请输入" maxLength={5}/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('goodsSts', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="1">上架</Option>
                  <Option value="2">下架</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="所属App">
              {getFieldDecorator('appType', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="1">小萌早教</Option>
                  <Option value="2">小萌绘本</Option>
                  <Option value="3">萌萌乐卡通</Option>
                  <Option value="4">萌萌儿歌</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="标签">
              {getFieldDecorator('labelName')(<Input placeholder="请输入" maxLength={10}/>)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit" onClick={() => this.handleSearch()}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            {/* <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a> */}
          </span>
        </div>
      </Form>
    );
  }


  _changeContentStatus(goodsSts, list) {
    if (list && list.length > 0) {
      let recordList = [];
      for (let i in list) {
        let one = { goodsId: list[i].goodsId }
        recordList.push(one)
      }

      if (goodsSts == 1) {  //上架
        if (recordList) {
          this.props.dispatch({
            type: 'content/upGoodsList',
            payload: { goodsList: recordList },
            callback: () => this.callback()
          });
        }
      } else if (goodsSts == 2) {
        if (recordList) {
          this.props.dispatch({
            type: 'content/downGoodsList',
            payload: { goodsList: recordList },
            callback: () => this.callback()
          });
        }
      } else if (goodsSts == 3) {
        if (recordList) {
          this.props.dispatch({
            type: 'content/delGoodsList',
            payload: { goodsList: recordList },
            callback: () => this.callback()
          });
        }
      }
    } else {
      message.error('请选择内容')
    }
  }

  callback() {
    this.handleSearch()
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    const contentList = this.props.contentList;
    const pagination = this.props.pagination;

    console.log('contentListcontentListcontentListcontentList', contentList)

    const tableData = {}
    tableData['list'] = contentList;
    tableData['pagination'] = pagination;
    console.log('tableDatatableDatatableData:', tableData)

    const {
      content: { data },
      loading,
    } = this.props;
    const { selectedRows } = this.state;

    const columns = [
      {
        title: '内容Id',
        dataIndex: 'goodsId',
        key: 'goodsId',
      },
      {
        title: '封面',
        dataIndex: 'goodsImg',
        key: 'goodsImg',
        render(text, record) {
          return <img src={imgPrex + text} alt={record.title} style={{ width: 30, height: 30 }} />;
        },
      },
      {
        title: '内容名称',
        dataIndex: 'goodsName',
        key: 'goodsName',
      },
      {
        title: '所属App',
        dataIndex: 'appType',
        key: 'app',
        render(text, record) {
          return <span>{text == '1' ? '小萌早教' : text == '2' ? '小萌绘本' : text == '3' ? '萌萌乐视频' : text == '4' ? '萌萌乐儿歌' : '其他'}</span>;
        },
      },
      {
        title: '作者',
        dataIndex: 'authorName',
        key: 'authorName',
      },
      {
        title: '状态',
        dataIndex: 'goodsSts',
        key: 'goodsSts',
        render(val) {
          return <span>{val == '1' ? '上架' : val == '2' ? '下架' : '已发布'}</span>;
        },
      },
      {
        title: '价格',
        dataIndex: 'price',
        key: 'price',
        render(val) {
          return <span>{val == 'null' ? '' : val}</span>;
        },
      },
      {
        title: '标签',
        dataIndex: 'labelList',
        render(vals) {
          return (
            <Fragment>
              {vals.map(v => (
                <Tag key={v.labelId} color="#108ee9">
                  {v.labelName}
                </Tag>
              ))}
            </Fragment>
          );
        },
      },
      {
        title: '操作',
        key: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this._editContent(record)}>编辑</a>
            <Divider type="vertical" />
            {record.goodsSts === 1 ? <a onClick={() => this._changeContentStatus(2, [{ goodsId: record.goodsId }])}>下架</a> : <a onClick={() => this._changeContentStatus(1, [{ goodsId: record.goodsId }])}>上架</a>}
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={this.handlAdd}>
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Popconfirm title={"你确定要上架选择的" + this.state.selectedRows.length + "个选项吗?"} placement="bottom" onConfirm={() => this._changeContentStatus(1, selectedRows)} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="primary" icon="upload" >
                      上架
                    </Button>
                  </Popconfirm>
                  <Popconfirm title={"你确定要下架选择的" + this.state.selectedRows.length + "个选项吗?"} placement="bottom" onConfirm={() => this._changeContentStatus(2, selectedRows)} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="primary" icon="download" >
                      下架
                    </Button>
                  </Popconfirm>
                  <Popconfirm title={"你确定要删除选择的" + this.state.selectedRows.length + "个选项吗?"} placement="bottom" onConfirm={() => this._changeContentStatus(3, selectedRows)} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="primary" icon="download" >
                      删除
                    </Button>
                  </Popconfirm>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              rowKey={'goodsId'}
              data={tableData}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
